package cn.itsource.utils;

import cn.itsource.org.domain.Employee;
import cn.itsource.org.service.IEmployeeService;
import cn.itsource.user.domain.LoginInfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

public class LoginContext {



    //返回当前登录用户的方法
    public static Object getCurrent(HttpServletRequest request){
        //1.获取当前系统的登录用户
        //1.1 从请求头里面获取token
        String token = request.getHeader("TOKEN");

        //从没有被spring管理的 类下面获取 spring管理对象
        WebApplicationContext applicationContext = WebApplicationContextUtils
                .getWebApplicationContext(request.getServletContext());
        //从容器里面获取想要的对象
        RedisTemplate redisTemplate = applicationContext.getBean("redisTemplate", RedisTemplate.class);

        //1.2 从redis里面获取相关 loginInfo
        LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(token);
        //1.3 根据loginInfo 获取User对象
        if (loginInfo.getType()==1){//判断前端用户
            IUserService userService = applicationContext.getBean(IUserService.class);
            User user=userService.loadById(loginInfo.getUId());
            return user;
        }else {
            IEmployeeService employeeService = applicationContext.getBean(IEmployeeService.class);
            Employee employee = employeeService.loadById(loginInfo.getUId());
            return employee;
        }

    }
}
